import java.security.SecureRandom;
import java.util.concurrent.Phaser;
import java.util.stream.IntStream;

public class PhaserMain {

    public static void main(String[] args) {
        Phaser phaser = new Phaser(10);

        IntStream.range(0, 10).forEach(index -> {
            new Thread(() -> {
                long start = System.currentTimeMillis();
                System.out.println(Thread.currentThread().getName() + " start");
                try {
                    Thread.sleep(new SecureRandom().nextInt(10) * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                long end = System.currentTimeMillis();
                System.out.println(Thread.currentThread().getName() + " done, duration: " + (end - start));


                if (index == 9) {
                    new Thread(() -> {
                        phaser.register();
                        long addtionalStart = System.currentTimeMillis();
                        System.out.println(Thread.currentThread().getName() + " start");
                        try {
                            Thread.sleep(20000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        long addtionalEnd = System.currentTimeMillis();
                        System.out.println(Thread.currentThread().getName() + " done, duration: " + (addtionalEnd - addtionalStart));

                        phaser.arrive();
                    }).start();
                }

                phaser.arrive();
            }).start();

        });

        phaser.awaitAdvance(phaser.getPhase());

        System.out.println(Thread.currentThread().getName() + " done");
    }
}
